package com.common.help.test13;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class NIOClient {

	int port;
	SocketChannel client;
	Selector selector;
	private ByteBuffer send = ByteBuffer.allocate(2048);
	private ByteBuffer recive = ByteBuffer.allocate(2048);
	public NIOClient(int port) throws IOException{
		client = SocketChannel.open();
		client.configureBlocking(false);
		client.connect(new InetSocketAddress("localhost",port));
		
		selector = Selector.open();
		
		client.register(selector, SelectionKey.OP_CONNECT);
		}
		
	public void session() throws IOException{
		if(client.isConnectionPending()){
			client.finishConnect();
			System.out.println("客户端已连接 服务端口: "+this.port);
			System.out.println("请登记姓名");
			client.register(selector, SelectionKey.OP_WRITE);
			Scanner sc = new Scanner(System.in);
			while(sc.hasNext()){
				String name = sc.next();
				if("".equals(name)){
					continue;
				}
					process(name);
				}
		}
	}
	
	
	private void process(String name) throws IOException {
		while(true){
			int i = selector.select();//判断当前有没有 客户排队
			if(i == 0){continue;}
			
			Set<SelectionKey> keys = selector.selectedKeys();
			Iterator<SelectionKey> iterator = keys.iterator();
			while(iterator.hasNext()){
				SelectionKey selectionKey = iterator.next();
				if(selectionKey.isWritable()){
					send.clear();
					send.put(name.getBytes());
					send.flip();
					client.write(send);
					client.register(selector, SelectionKey.OP_READ);
				}
			}
		}
	}

	public static void main(String[] args) throws IOException {
		new NIOClient(8080).session();
	}
}
